//对axios进行封装
import axios from 'axios'
const myAxios = axios.create({
  baseURL: 'http://localhost:3000',
  timeout: 5000,
})
  
//配置请求拦截器   添加token
myAxios.interceptors.request.use((config) => {
  //拦截成功，给请求头添加token
  const token = localStorage.token;
  config.headers.Authorization = token;
  return config
}, (err) => {
  //拦截失败
  return err
})

//配置响应拦截器    报错处理
myAxios.interceptors.response.use((res) => {
  return res
}, (err) => {
  //响应失败
  if(err && err.response) {
    //对错误类型进行判断
    switch (err.response.status) {
      case 400: err.message = '请求错误（400）'; break;
      case 401: err.message = '身份认证失败（401）'; break;
      default: err.message = `连接出错(${err.response.status})`; break;
    }

    return {
      status: 0,
      message: err.message
    }
  }
  return {
    status: 0,
    message: '服务器连接失败'
  }
})

export default myAxios